<template>
  <el-dialog 
    v-el-drag-dialog="{drag: true, full: false, resize: false}"
    :visible="true"
    :close-on-click-modal="false"
    @close="closeMd"
    :title="'拆分订单'"
    width="90%">
    <div ref="dgtools" class="filter-container">
        <div class="dgts-row" style="line-height: 28px;">
            <el-button type="primary" style="margin-right: 15px;" @click="selOrder">拆分</el-button>

            <label>客户：<span>{{order.useCarCus.realName}}</span></label>
            <label>操作员：<span>{{order.operatorCus.realName}}</span></label>
            <label>联系人：<span>{{order.routeLink.name}}</span></label>
            <label>联系电话：<span>{{order.routeLink.phone}}</span></label>
            <label>业务员：<span>{{order.serviceMan.name}}</span></label>
            <label>原行程总价：<span>{{order.orderTotalPrice}}￥</span></label>
            <label>拆分后合计总价：<span>{{dg.splitOrderTotalPrice}}￥</span></label>
        </div>
    </div>

    <div style="min-width: 1600px">
        <el-table
            :ref="dg.tbName"
            :data="dayRoutes"
            border fit
            :height="'200'"
            :max-height="'600'"
            :row-class-name="rowClassName"
            @header-dragend="dragHeaderSp"
            @selection-change="selSpRowChange">
            <template slot="empty">未查询到数据</template>

            <el-table-column fixed="left" type="selection" width="40"></el-table-column>
            <el-table-column
                prop="goDate"
                label="日期"
                :resizable="false"
                width="90">
            </el-table-column>

            <el-table-column
                prop="stime"
                label="开始时间"
                :resizable="false"
                width="70"
            >
            </el-table-column>

            <el-table-column
                prop="spoint.name"
                label="出发地点">
            </el-table-column>

            <el-table-column
                prop="amPoints"
                label="上午行程"
                width="400">
                <template slot-scope="scope">
                    <ol style="margin: 0; padding: 10px;">
                        <li v-for="it in scope.row.amPoints" :key="it.id">{{it.name}}</li>
                    </ol>
                </template>
            </el-table-column>

            <el-table-column
                prop="lunchPoint.name"
                label="午餐地点">
            </el-table-column>

            <el-table-column
                prop="pmPoints"
                label="下午行程"
                width="400">
                <template slot-scope="scope">
                    <ol style="margin: 0; padding: 10px;">
                        <li v-for="it in scope.row.pmPoints" :key="it.id">{{it.name}}</li>
                    </ol>
                </template>
            </el-table-column>

            <el-table-column
                prop="dinnerPoint.name"
                label="晚餐地点">
            </el-table-column>

            <el-table-column
                prop="epoint.name"
                label="结束地点">
            </el-table-column>

            <el-table-column
                prop="etime"
                label="结束时间"
                :resizable="false"
                width="70"
            >
            </el-table-column>
        </el-table>
    </div>

    <div class="split-order-list">
        <div v-if="splitOrderList.length == 0" class="c-gray" style="padding-left: 15px;">没有选择行程！</div>

        <template v-else>
            <ul class="right-dates">
                <li v-for="(it, i) in splitOrderList" :key="i" :class="splitItemIndex == i ? 'curr' : ''" @click="selSplitItem(i, it)">
                    <div class="date">{{it.sedate}}</div>
                    <div class="time">{{it.setime}}</div>
                    <div class="btns">
                        <template>
                            <el-popover v-if="it.newDrs.length == 1"
                                placement="top"
                                v-model="it.ssVisible"
                            >
                                <SetSplitTime :myData="it" @myClick="splitOrder"></SetSplitTime>
                                <u slot="reference">拆</u>
                            </el-popover>
                        </template>
                        
                        <u @click.prevent="delOrder(i, it)">删</u>
                    </div>
                </li>
            </ul>

            <div class="left-fm">
                <div class="route-point">
                    <el-table
                        :data="fm.ps.newDrs"
                        border
                        :max-height="'400'"
                        :ref="'routePointTb'"
                    >
                        <template slot="empty">没有行程数据</template>

                        <el-table-column
                            prop="goDate"
                            label="出发日期"
                            :resizable="false"
                            width="120">
                            <template slot-scope="scope">{{scope.row.goDate | time('yyyy年MM月dd号')}}</template>
                        </el-table-column>

                        <el-table-column
                            prop="spoint.name"
                            label="出发地点"
                            width="200">
                        </el-table-column>

                        <el-table-column
                            prop="stime"
                            label="开始时间"
                            :resizable="false"
                            width="70">
                            <template slot-scope="{row}">{{row.stime.split(' ')[1]}}</template>
                        </el-table-column>

                        <el-table-column
                            prop="amPoints"
                            label="上午行程"
                            width="auto">
                            <template slot-scope="scope">
                                <ol style="margin: 0; padding-left: 10px;">
                                    <li v-for="it in scope.row.amPoints" :key="it.id">{{it.name}}</li>
                                </ol>
                            </template>
                        </el-table-column>

                        <el-table-column
                            prop="lunchPoint.name"
                            label="午餐地点"
                            width="190">
                        </el-table-column>

                        <el-table-column
                            prop="pmPoints"
                            label="下午行程"
                            width="auto">
                            <template slot-scope="scope">
                                <ol style="margin: 0; padding-left: 10px;">
                                    <li v-for="it in scope.row.pmPoints" :key="it.id">{{it.name}}</li>
                                </ol>
                            </template>
                        </el-table-column>

                        <el-table-column
                            prop="dinnerPoint.name"
                            label="晚餐地点"
                            width="190">
                        </el-table-column>

                        <el-table-column
                            prop="epoint.name"
                            label="结束地点"
                            width="190">
                        </el-table-column>

                        <el-table-column
                            prop="etime"
                            label="结束时间"
                            :resizable="false"
                            width="70">
                            <template slot-scope="{row}">{{row.etime.split(' ')[1]}}</template>
                        </el-table-column>
                    </el-table>
                </div>

                <el-form 
                    :model="fm.ps" 
                    :ref="fm.fname">
                    <el-row type="flex">
                        <el-form-item 
                            label="运价"
                            label-width="60px"
                            prop="transportPrice" 
                            :rules="[
                                { required: true, message: '请输入运价', trigger: 'blur' },
                                this.$rules.isFloat()
                            ]">
                        <el-input 
                            v-model.number="fm.ps.transportPrice" 
                            placeholder="运价"
                            @blur="calcOrderTotalPrice"
                            style="width: 80px;"
                        ><span slot="suffix">￥</span></el-input>
                        </el-form-item>

                        <el-form-item 
                            label="其他费用"
                            label-width="80px"
                            prop="otherFees" 
                            :rules="[
                                { required: false, message: '请输入其他费用', trigger: 'blur' },
                                this.$rules.isFloat()
                            ]">
                            <el-input 
                                v-model.number="fm.ps.otherFees" 
                                placeholder="其他费用"
                                @blur="calcOrderTotalPrice"
                                style="width: 80px;"
                            ><span slot="suffix">￥</span></el-input>
                        </el-form-item>

                        <el-form-item 
                            label="师傅现收"
                            label-width="80px"
                            prop="remindRouteCash" 
                            :rules="[
                                { required: false, message: '请输入师傅现收', trigger: 'blur' },
                                this.$rules.isFloat()
                            ]">
                            <el-input 
                                v-model.number="fm.ps.remindRouteCash" 
                                placeholder="师傅现收"
                                style="width: 80px;"
                            ><span slot="suffix">￥</span></el-input>
                        </el-form-item>

                        <el-form-item 
                            label="订单总价" 
                            label-width="80px"
                            prop="orderTotalPrice">
                            <el-input 
                                v-model.number="fm.ps.orderTotalPrice" 
                                placeholder="自动计算"
                                :readonly="true"
                                style="width: 80px;"
                            ><span slot="suffix">￥</span></el-input> 
                        </el-form-item>

                        <el-form-item 
                            label="途径高速"
                            label-width="80px"
                            prop="wayHighSpeed" 
                            :rules="[
                                { required: false, message: '请输入途径高速', trigger: 'blur' }
                            ]">
                            <el-input 
                                v-model="fm.ps.wayHighSpeed" 
                                placeholder="途径高速"
                                maxlength="50"
                                show-word-limit
                                @blur="setRouteDetail(fm.ps.index)"
                                style="width: 250px"
                            ></el-input>
                        </el-form-item>

                        <el-form-item 
                            label="行程简称"
                            prop="routeShort" 
                            label-width="90px"
                            :rules="[
                                { required: true, message: '请输入行程简称', trigger: 'blur' },
                                { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
                            ]">
                            <el-input 
                                v-model="fm.ps.routeShort" 
                                placeholder="行程简称"
                                maxlength="15"
                                show-word-limit
                            ></el-input>
                        </el-form-item>

                        <el-form-item 
                            label="业务类型" 
                            prop="orderServiceType"
                            label-width="90px"
                            :rules="[{ required: true, message: '请选择业务类型', trigger: 'blur' }]">
                                <el-select 
                                    style="width: 120px"
                                    v-model="fm.ps.orderServiceType" 
                                    :placeholder="'业务类型'">
                                    <el-option :label="'县际业务'" :value="'COUNTY_SER'"></el-option>
                                    <el-option :label="'市际业务'" :value="'CITY_SER'"></el-option>
                                    <el-option :label="'省际业务'" :value="'PROVINCE_SER'"></el-option>
                                </el-select>
                        </el-form-item>
                    </el-row>

                    <el-row :gutter="10" class="text-note">
                        <el-col :span="9">
                            <el-form-item 
                            label="行程"
                            prop="routeDetail" 
                            label-width="35px"
                            >
                            <el-input
                                type="textarea"
                                autosize
                                placeholder="行程详情内容（不能修改）"
                                v-model="fm.ps.routeDetail"
                                :readonly="true"
                            >
                            </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item 
                            label="客户备注"
                            prop="routeDetail" 
                            label-width="35px"
                            >
                            <el-input
                                type="textarea"
                                autosize
                                placeholder="客户备注（所有人都能看到）"
                                maxlength="100"
                                show-word-limit
                                v-model="fm.ps.cusNote"
                            >
                            </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item 
                            label="驾驶员备注"
                            prop="driverNote" 
                            label-width="35px"
                            >
                            <el-input
                                type="textarea"
                                autosize
                                placeholder="驾驶员备注内容"
                                maxlength="100"
                                show-word-limit
                                v-model="fm.ps.driverNote"
                            >
                            </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item 
                            label="业务员备注"
                            prop="salesmanNote" 
                            label-width="35px"
                            >
                            <el-input
                                type="textarea"
                                autosize
                                placeholder="业务员备注内容"
                                maxlength="100"
                                show-word-limit
                                v-model="fm.ps.salesmanNote"
                            >
                            </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </template>
    </div>
    <div style="text-align: center; padding-bottom: 10px;">
        <el-button type="primary" :disabled="fm.sb.load" @click="submitFm">{{fm.sb.text}}</el-button>
    </div>
 </el-dialog>
</template>

<script>
import { mapGetters } from "vuex";
import DataGridBase from '@/views/mixins/DataGridBase';
import elDragDialog from '@/directive/el-drag-dialog';
import UploadImg from "@/components/UploadImg";
import SetSplitTime from './set-split-time';

import * as orderService from '@/api/services/order.service';

export default {
  name: 'SplitOrder',
  mixins: [ DataGridBase ],
  directives: { elDragDialog },
  components: { UploadImg, SetSplitTime },
  props: { myData: Object },
  computed: {
    ...mapGetters(["uname"]),
  },
  data() {
    let order = this.myData.order;
    return {
        order: order,
        dg: {
            tbName: 'splitOrderTb',
            // 所选行数组
            selRows: [], 
            list: [],
            ps: { // 过滤参数
                page: 1, row: 100,
            },
            // 拆分后合计总价
            splitOrderTotalPrice: order.orderTotalPrice
        },
        // 每日行程
        dayRoutes: order.dayRoutes || [],
        // 拆分订单
        splitOrderList: [],
        // 选中的车分行程下标
        splitItemIndex: 0,
        // 拆分行程表单
        fm: {
            fname: 'splitOrderFm',
            sb: { load: false, text: '保存拆分' },
            ps: {}
        },
        
    }
  },
  created(){
    const that = this;

    console.log('欲拆分的订单对象：', this.order);
  },
  methods:{
    closeMd(){ // 关闭弹框
        this.$emit('myClick', false);
    },
    /** 选中数据改变事件 */
    selSpRowChange(rows){
        this.dg.selRows = rows;
    },
    /**
     * 拆分日期时间
     * drs 每日行程数组
     */
    splitDateTime(drs){
        let that = this, U = that.U;

        let sedate = '', setime = '';
        if(drs.length > 0){
            // 第一天开始日期时间 最后一天完团日期时间
            let sd = drs[0].stime, ed = drs[drs.length - 1].etime;
            // 第一天开始日期 最后一天完团日期
            let sdate = sd.split(' ')[0], edate = ed.split(' ')[0];
            // 第一天开始时间 最后一天完团时间
            let stime = sd.split(' ')[1], etime = ed.split(' ')[1];

            if(sdate == edate){
                // 日期一样，说明是同一天
                sedate = U.datefmt(sd, 'MM月dd号');
            }else{
                // 日期不一样
                sedate = U.datefmt(sd, 'MM月dd号')+'~'+U.datefmt(ed, 'MM月dd号');
            }

            // 起止时间
            setime = stime+'~'+etime;

            return [sedate, setime];
        }

        return '';
    },
    // 选择订单进行拆分
    selOrder(){
        let that = this, U = that.U, o = that.order, rows = that.dg.selRows;

        if(rows.length == 0){
            U.qerror('至少选择一条数据');
        }else{
            let so = that.handlerSplitOrderRows(rows);
            // console.log('合并后的拆分行程数组数据', so);
            if(so){
                // 此处需要深度拷贝，不然会影响列表数据
                that.splitOrderList.push(U.scopy(so));
                that.fm.ps = that.splitOrderList[that.splitOrderList.length - 1];
                // 设置当前被拆分的订单下标
                that.splitItemIndex = that.splitOrderList.length - 1;
            }
            // console.log('拆分订单数据', that.splitOrderList);
        }
    },
    // 处理拆分行程数组数据
    handlerSplitOrderRows(rows){
        let that = this, U = that.U, o = that.order;

        // 根据对象index属性升序排序
        rows = U.sortByKey(rows, 'index');
        // console.log('排序后：选择的原始数据数组', rows);
        // 循环数据保存天行程
        let newDrs = [], fg = true;
        for(let i = 0; i < rows.length; i++){
            let it = rows[i];
            // 为每条选中的数据添加一个isSplit=true参数，表示已经被拆分；
            // 如果选中的多条，则在显示当前数据时，根据newDrs的条数判断，多条不显示‘拆’，单条才显示，当删除拆分订单后，对应的原始行数据的isSplit=false，表示没有被拆分；
            if(it.isSplit) {
                fg = U.qerrorFalse(it.goDate+'行程已被拆分，请选择其他行程！');
                break;
            }else{
                it.isSplit = true;

                newDrs.push({
                    id: it.id, // 取消时需要
                    goDate: it.goDate,
                    spoint: it.spoint,
                    stime: `${it.goDate} ${it.stime}`,
                    amPoints: it.amPoints,
                    lunchPoint: it.lunchPoint,
                    pmPoints: it.pmPoints,
                    dinnerPoint: it.dinnerPoint,
                    epoint: it.epoint,
                    etime: `${it.goDate} ${it.etime}`,
                    emptyTimes: it.emptyTimes,
                    seStaInfo: it.seStaInfo,
                });
            }
        }
        if(!fg) return null;
        
        console.log('拆分标题', that.splitDateTime(newDrs));
        let sedate = that.splitDateTime(newDrs)[0];
        let setime = that.splitDateTime(newDrs)[1];
        let so = { 
            // 下标
            index: that.splitOrderList.length,
            // 拆分时间点显示/隐藏
            ssVisible: false,
            // 新的每日行程
            newDrs: newDrs,
            // 显示的起止日期
            sedate: sedate,
            // 显示的起止时间（对应开始日期的开始时间，结束日期的结束时间）
            setime: setime,
            // 运价 
            transportPrice: o.transportPrice,
            // 其他费用
            otherFees: o.otherFees,    
            // 师傅现收  
            remindRouteCash: o.remindRouteCash,  
            // 订单总价   
            orderTotalPrice: o.orderTotalPrice,    
            // 途径高速
            wayHighSpeed: o.wayHighSpeed,     
            // 业务类型 订单业务类型(必填) eg:COUNTY_SER县际业务 CITY_SER市际业务 PROVINCE_SER省际业务
            orderServiceType: o.orderServiceType,
            // 行程简称
            routeShort: '',  
            // 行程详情
            routeDetail: o.routeDetail,  
            // 客户备注
            cusNote: o.cusNote,     
            // 驾驶员备注           
            driverNote: o.driverNote,         
            // 业务员备注    
            salesmanNote: o.salesmanNote
        };
        // 重新生成信息的行程详情
        so.routeDetail = that.createRouteDetail(so);

        return so;
    },
    /**
     * 选择拆分项
     * @param i 选中的对象所在数组下标
     * @param it 选中的对象
     */
    selSplitItem(i, it){
        const that = this;

        if(i != that.splitItemIndex){
            that.splitItemIndex = i;
            that.fm.ps = that.splitOrderList[i];

            // 重新渲染表格
            that.$refs['routePointTb'].doLayout();
        }
    },
    /**
     * 拆分空闲时间列表
     * 空闲时间按照时间段的顺序排序
     * @param goDate    出发日期
     * @param list      原始空闲时间列表
     * @param time      拆分时间点
     * @returns [前一个数组, 后一个数组]
     */
    splitEmptys(goDate, list, time){
        let that = this, arr = [];
        
        if(!list || list.length == 0) return [[], []];

        // 将时间点转换成时间类型，方便比较
        let t = that.U.str2date(`${goDate} ${time}`);

        // 将空闲时间数组按照起止时间排序
        let splitIndex1 = '', splitIndex2 = '';
        for(let i = 0; i < list.length; i++){
            let st = that.U.str2date(`${goDate} ${list[i].stime}`);
            let et = that.U.str2date(`${goDate} ${list[i].etime}`);

            if(et >= t && st <= st){
                splitIndex1 = list[i].no; // 此项需要删除
                break;
            }else if(t < st){
                splitIndex2 = list[i].no; // 此项需要不删除且划分到后面
                break;
            }
        }

        // 找出拆分时间点是否在其中一段起止时间内，没有这找出时间点距最近开始时间的空闲时间项作为分隔点
        if(splitIndex1){
            let prevArr = list.slice(0, splitIndex1) || [];
            let nextArr = list.slice(splitIndex1+1) || [];

            arr = [prevArr, nextArr];
        }else if(splitIndex2){
            let prevArr = list.slice(0, splitIndex1) || [];
            let nextArr = list.slice(splitIndex1) || [];

            arr = [prevArr, nextArr];
        }else{// 没有小于时间点的空闲时间段，则所有都归上一个
            let prevArr = list.slice(0);
            arr = [prevArr, []];
        }

        return arr;
    },
    /**
     * 拆分-指定时间段行程
     * @param e 传入的数据
     */
    splitOrder(e){
        let that = this, curIndex = that.splitItemIndex;
        console.log('再次拆分的数据', e);
        if(e == false){
            that.splitOrderList[curIndex].ssVisible = false;
        }else{
            // 所选拆分订单所在下标, 拆分时间点, 拆分地点下标, 拆分地点名称
            let time = e.time, pointIndex = e.pointIndex, point = e.point;
            
            // 当前拆分的行程数据, 新复制一份行程数据作为新的数据对象
            let oldObj = that.splitOrderList[curIndex], newObj = that.U.scopy(oldObj);
            newObj.ssVisible = false; // 默认关闭拆分设置
            newObj.index = parseInt(newObj.index)+1;// 增加下标

            // 旧天行程, 新天行程
            let newDr = newObj.newDrs[0], oldDr = oldObj.newDrs[0];

            // 修改-旧-结束时间
            oldDr.etime = oldDr.etime.split(' ')[0]+' '+time;
            // 修改-新-开始时间
            newDr.stime = newDr.stime.split(' ')[0]+' '+time;

            // 处理显示时间
            let oldSplitDateTime = that.splitDateTime([oldDr]);
            oldObj.sedate = oldSplitDateTime[0];
            oldObj.setime = oldSplitDateTime[1];
            let newSplitDateTime = that.splitDateTime([newDr]);
            newObj.sedate = newSplitDateTime[0];
            newObj.setime = newSplitDateTime[1];

            // 修改-旧-结束地点
            oldDr.epoint = point;
            // 修改-新-开始地点
            newDr.spoint = point;

            // 处理空闲时间
            let emptys = that.splitEmptys(oldDr.stime.split(' ')[0], oldDr.emptyTimes, time);
            oldDr.emptyTimes = emptys[0];
            newDr.emptyTimes = emptys[1];

            // 处理站点信息
            if(oldDr.epoint.isSta){
                // 如果终点是站点，则站点信息归新行程，新行程不保存途径站点信息
                let seStaInfo = oldDr.seStaInfo;
                oldDr.seStaInfo = null;
                newDr.seStaInfo = seStaInfo;
                newDr.wpStaInfos = [];
            }else{
                // 无论起点是否是站点，站点信息都保存至旧行程，途径站点信息也保存至旧行程，则此处不做处理
            }

            /***********处理新旧数据地点--begin***************/
            let i = -1;// 初始地点下标

            // 拆分地点是否在上午行程地点数组中
            for(let a = 0; a < oldDr.amPoints.length; a++){
                i++; // 增加下标

                // 地点和地点下标都一致，则当前点在上午行程中
                if(i == pointIndex && oldDr.amPoints[a].name == point.name){
                    // 存在下一个
                    if(oldDr.amPoints.length > a + 1){
                        let amArr = oldDr.amPoints;
                        // 1.将除当前点之后的点保存为新行程的上午行程地点
                        newDr.amPoints = amArr.slice(a+1);
                        // 2.之前的点为旧行程的上午行程地点（不包含当前点）
                        oldDr.amPoints = amArr.slice(0, a);

                        // 3.旧行程-午餐地点为空、下午行程地点为空、晚餐地点为空
                        oldDr.lunchPoint = '';
                        oldDr.pmPoints = [];
                        oldDr.dinnerPoint = '';
                    }else{// 没有下一个
                        // 1.新旧对象的上午行程数组都为空
                        oldDr.amPoints = [];
                        newDr.amPoints = [];

                        // 2.旧-午餐地点、下午行程数组、完成地点都为空
                        oldDr.lunchPoint = '';
                        oldDr.pmPoints = [];
                        oldDr.dinnerPoint = '';
                    }

                    // 将新数据对象添加进列表
                    newObj.newDrs[0] = newDr;
                    that.splitOrderList.push(newObj);
                    break;
                }
            }


            if(oldDr.lunchPoint){
                i++; // 增加下标

                // 地点和地点下标都一致，则当前点是午餐地点
                if(i == pointIndex && oldDr.lunchPoint.name == point.name){
                    // 1.旧行程上午行程地点不变，午餐地点为空、下午行程地点为空、晚餐地点为空；
                    oldDr.lunchPoint = '';
                    oldDr.pmPoints = [];
                    oldDr.dinnerPoint = '';
                    // 2.新行程的上午行程为空，午餐地点为空、下午行程地点不变、晚餐地点不变；
                    newDr.amPoints = [];
                    newDr.lunchPoint = '';

                    // 将新数据对象添加进列表
                    newObj.newDrs[0] = newDr;
                    that.splitOrderList.push(newObj);
                }
            }
            

            // 拆分地点是否在下午行程地点数组中
            for(let a = 0; a < oldDr.pmPoints.length; a++){
                i++; // 增加下标

                // 地点和地点下标都一致，则当前点在下午行程中
                if(i == pointIndex && oldDr.pmPoints[a].name == point.name){
                    // 存在下一个
                    if(oldDr.pmPoints.length > a + 1){
                        let pmArr = oldDr.pmPoints;
                        // 1.将除当前点之后的点保存为新行程的下午行程地点
                        newDr.pmPoints = pmArr.slice(a+1);
                        // 2.之前的点为旧行程的下午行程地点（不包含当前点）
                        oldDr.pmPoints = pmArr.slice(0, a);

                        // 3.旧行程-晚餐地点为空
                        oldDr.dinnerPoint = '';

                        // 4.新行程-上午行程为空、午餐地点为空
                        newDr.amPoints = [];
                        newDr.lunchPoint = '';
                    }else{// 没有下一个
                        // 1.新旧对象的下午行程地点都为空
                        oldDr.pmPoints = [];
                        newDr.pmPoints = [];

                        // 2.旧行程-晚餐地点为空
                        oldDr.dinnerPoint = '';

                        // 3.新行程-上午行程为空、午餐地点为空
                        newDr.amPoints = [];
                        newDr.lunchPoint = '';
                    }

                    // 将新数据对象添加进列表
                    newObj.newDrs[0] = newDr;
                    that.splitOrderList.push(newObj);
                    break;
                }
            }


            if(oldDr.dinnerPoint){
                i++; // 增加下标

                // 地点和地点下标都一致，则当前点是晚餐地点
                if(i == pointIndex && oldDr.dinnerPoint.name == point.name){
                    // 1.旧行程上午行程地点不变，午餐地点不变、下午行程地点不变、晚餐地点为空；
                    oldDr.dinnerPoint = '';
                    // 2.新行程的上午行程为空，午餐地点为空、下午行程地点为空、晚餐地点为空；
                    newDr.amPoints = [];
                    newDr.lunchPoint = '';
                    newDr.pmPoints = [];
                    newDr.dinnerPoint = '';

                    // 将新数据对象添加进列表
                    newObj.newDrs[0] = newDr;
                    that.splitOrderList.push(newObj);
                }
            }
            /***********处理新旧数据地点--end*****************/

            // 设置-新行程的行程详情
            that.setRouteDetail(that.splitOrderList.length - 1);
            // 设置-旧行程的行程详情（最后设置旧行程，因为当前选中的是旧行程）
            that.setRouteDetail(that.splitOrderList.length - 2);

            oldDr.ssVisible = false;
        }
    },
    /**
     * 删除-指定时间段行程
     * @param i 拆分订单列表下标
     * @param it 拆分的订单对象
     */
    delOrder(i, it){
        const that = this;

        that.U.qconfim('确定删除该拆分行程吗？').then(r => {
            if(r){
                that.splitOrderList.splice(i, 1);

                // 设置原始订单的每日行程的isSplit=false
                it.newDrs.forEach(ita => {
                    that.dayRoutes.find(itb => {
                        if(ita.id == itb.id) itb.isSplit = false;
                    });
                });
            }
        });
    },
    // 计算订单总价 
    calcOrderTotalPrice(){
      const that = this, FV = that.FV, ps = that.fm.ps;

      let totalPrice = 0;

      // 验证并累计运价
      if(FV.isNumber(ps.transportPrice) && ps.transportPrice){
        totalPrice += parseFloat(ps.transportPrice);
      }

      // 验证并累计其他费用
      if(FV.isNumber(ps.otherFees) && ps.otherFees){
        totalPrice += parseFloat(ps.otherFees);
      }

      ps.orderTotalPrice = totalPrice;
    },
    /**
     * 生成行程详情
     * @param row 拆分行程项
     * @param 行程详情
     */
    createRouteDetail(row){
        let that = this, U = that.U, drs = row.newDrs, resArr = [];
        
        drs.forEach((it, index) => {
            let rdText = '';
            
            // 出发时间 03月01日08:00
            rdText += that.U.datefmt(it.stime, 'MM月dd号 HH:mm').replace(' ', '');

            // 开始地址
            rdText += it.spoint.name;

            // 接EU6668 || 接团
            if(it.seStaInfo){
                rdText += it.seStaInfo.jsType == 1 ? `接${it.seStaInfo.flightTrainNo}` : `接团`;
            }else{
                rdText += '接团';
            }

            // 上午行程地址 都江堰→青城山
            if(it.amPoints){
                let amAddrs = '';
                it.amPoints.forEach(amit => { amAddrs += `→${amit.name}`; });
                if(amAddrs) rdText += amAddrs;
            }

            // 午餐地址 都江堰王鸡肉（本身午餐地点对象不为空，name可能为空）
            if(it.lunchPoint && it.lunchPoint.name) rdText += `→${it.lunchPoint.name}`;
            
            // 下午行程地址 街子古镇→怀远古镇
            if(it.pmPoints){
                let pmAddrs = '';
                it.pmPoints.forEach(pmit => { pmAddrs += `→${pmit.name}`; });
                if(pmAddrs) rdText += pmAddrs;
            }

            // 晚餐地址 崇州饭店
            if(it.dinnerPoint && it.dinnerPoint.name) rdText += `→${it.dinnerPoint.name}`;

            // 处理最后一个箭头（→），如果最后一位是箭头，则去掉
            if(rdText.lastIndexOf('→') == rdText.length - 1) rdText = rdText.slice(0, rdText.length - 1);
            
            // 结束时间 18点
            rdText += `，${it.etime.split(' ')[1]}`;
            // 如果结束时间小于开始时间，则表示跨天了，需要在后面加一个日期
            if(U.str2date(it.stime).getTime() > U.str2date(it.etime).getTime()){
                rdText += `（${U.addDayForTime(it.goDate, 1, 'MM月dd号')}）`
            }

            // 结束地址
            rdText += it.epoint.name;
            // 送EU668完团 || 完团
            if(it.seStaInfo){
                rdText += it.seStaInfo.jsType == 2 ? `送${it.seStaInfo.flightTrainNo}完团` : `完团`;
            }else{
                // 单天或者多天行程的最后一条，显示“完团” 多天，显示“入住”
                rdText += (drs.length == 1 || index == drs.length - 1) ? '完团' : '入住';
            }

            // 途径高速 （途径都汶高速、京昆高速）
            if(it.wayHighSpeed) rdText += '（途径'+it.wayHighSpeed+'）';

            resArr.push(rdText);
        });

        return resArr.join('@');
    },
    /**
     * 生成-行程详情
     * @param index 当前选中的拆分订单编号
     */
    setRouteDetail(index){
        const that = this;

        let it = that.splitOrderList[index];
        if(it){
            let rdText = that.createRouteDetail(it);

            that.fm.ps.routeDetail = rdText;
            that.splitOrderList[index].routeDetail = rdText;
        }
    },
    /**
     * 提交-表单
     */
    submitFm(){
        const that = this, U = that.U, list = that.splitOrderList, ps = {};

        console.log('原订单行程列表：', that.dayRoutes);
        console.log('拆分后的行程列表：', list);
        if(list.length == 0){
            U.qerror('请先选择一天行程再点击[拆分]按钮');
        }else if(list.length < 1 || (that.dayRoutes.length == 1 && list.length == 1)){
            U.qerror('至少拆分一次行程');
        }else{
            // 所有的结果数组
            let resArr = [];

            let tip = '', fg = true;
            // 遍历拆分行程数组，保存
            for(let i = 0; i < list.length; i++){
                let it = list[i];
              
                if(!it.transportPrice && it.transportPrice !== 0){
                    tip = '[运价]不能为空';
                }else if(!it.routeShort){
                    tip = '[行程简称]不能为空';
                }

                if(tip){
                    fg = U.qerrorFalse(`行程[${it.sedate} ${it.setime}]的${tip}`);
                    break;
                }else{
                   resArr.push(it);
                }
            }

            if(fg){
                // 遍历天行程，将没有被拆分的行程合并成一个行程，且是主行程，设置属性isOld=1，表示原订单
                let srcRows = [];
                that.dayRoutes.forEach(row => {
                    // 未被拆分isSplit为空 || 未定义 || false
                    if(!row.isSplit) srcRows.push(row);
                });

                let srcDr = that.handlerSplitOrderRows(srcRows);
                // 设置原订单的行程简称
                srcDr.routeShort = that.order.routeShort;
                // console.log('原订单行程', srcDr);
                
                resArr.unshift(srcDr);// 添加到第一位
            }

            // console.log('新的结果数组：', resArr);
            if(fg){
                // 拆分订单编号
                ps.splitOrderNum = that.order.orderNum;

                // 拆分后的订单信息
                let orderInfos = [];
                resArr.forEach((it, index) => {
                    // 每日行程
                    let dayRouteInfo = [];
                    it.newDrs.forEach(drit => {
                        // 出发日期
                        let goDate = drit.stime.split(' ')[0];

                        // 上午行程
                        let amPoints = []; 
                        drit.amPoints.forEach(amit => {
                            amPoints.push(`${amit.address}=${amit.lnglat}=${amit.area}=${amit.isSta ? 1 : 0}`);
                        });

                        // 下午行程
                        let pmPoints = []; 
                        drit.pmPoints.forEach(pmit => {
                            pmPoints.push(`${pmit.address}=${pmit.lnglat}=${pmit.area}=${pmit.isSta ? 1 : 0}`);
                        });

                        // 临空时间
                        let emptyTimes = [];
                        drit.emptyTimes.forEach(etit => {
                            emptyTimes.push({
                                // 临空开始时间
                                freeStime: `${goDate} ${etit.stime}`,
                                // 临空结束时间
                                freeEtime: `${goDate} ${etit.etime}`,
                                // 停靠位置
                                freeSpoint: `${etit.stopPoint.area.split('-')[1]} ${etit.stopPoint.name}=${etit.stopPoint.lnglat}=${etit.stopPoint.area}`,
                                // 返回位置
                                freeEpoint: `${etit.backPoint.area.split('-')[1]} ${etit.backPoint.name}=${etit.backPoint.lnglat}=${etit.backPoint.area}`
                            });
                        });

                        // 站点航班/车次查询信息数组
                        let staInfos = []; 
                        if(drit.seStaInfo) staInfos.push(`${drit.seStaInfo.flightTrainNo}=${drit.seStaInfo.downUpTime}=${drit.seStaInfo.type}=${drit.seStaInfo.jsType}=${drit.seStaInfo.selStaName}`);
                        if(drit.wpStaInfos) drit.wpStaInfos.forEach(wpit => {
                            staInfos.push(`${wpit.flightTrainNo}=${wpit.downUpTime}=${wpit.type}=${wpit.jsType}=${wpit.selStaName}`);
                        });

                        dayRouteInfo.push({
                            // 开始时间(必填) eg:2021-03-11 08:30
                            stime: drit.stime,
                            // 结束时间(必填) eg:2021-03-11 19:30
                            etime: drit.etime,
                            // 出发地点(必填) eg：成都市 天府广场=103.666666,30.666666=四川省-成都市-武侯区=isSta
                            spoint: `${drit.spoint.address}=${drit.spoint.lnglat}=${drit.spoint.area}=${drit.spoint.isSta ? 1 : 0}`,
                            // 上午行程(可为空,多个“/@”拼接) eg：成都市 宽窄巷子=103.666666,30.666666=四川省-成都市-武侯区/@成都市 锦里=103.666666,30.666666=四川省-成都市-武侯区
                            morningPoint: amPoints.join('/@'),
                            // 午餐地点(可为空) eg：成都市 新城市广场=103.666666,30.666666=四川省-成都市-武侯区
                            lunchPoint: drit.lunchPoint ? `${drit.lunchPoint.address}=${drit.lunchPoint.lnglat}=${drit.lunchPoint.area}=${drit.lunchPoint.isSta ? 1 : 0}` : null,
                            // 下午行程(可为空,多个“/@”拼接) eg：成都市 大熊猫基地=103.666666,30.666666=四川省-成都市-武侯区
                            afternoonPoint: pmPoints.join('/@'),
                            // 晚餐地点(可为空) eg：成都市 沙湾东一路=103.666666,30.666666=四川省-成都市-武侯区
                            dinnerPoint: drit.dinnerPoint ? `${drit.dinnerPoint.address}=${drit.dinnerPoint.lnglat}=${drit.dinnerPoint.area}=${drit.dinnerPoint.isSta ? 1 : 0}` : null,
                            // 到达地点(必填) eg：成都市 天府广场=103.666666,30.666666=四川省-成都市-武侯区=isSta
                            epoint: `${drit.epoint.address}=${drit.epoint.lnglat}=${drit.epoint.area}=${drit.epoint.isSta ? 1 : 0}`,
                            // 临空信息，数组形式
                            freeInfo: emptyTimes,
                            // 站点信息(可为空,多个“/@”拼接) eg:航班号=起点降落时间=位置类型=接送类型=站点名称
                            stationInfo: staInfos.join('/@')
                        });
                    });

                    // 拆分后的订单信息
                    orderInfos.push({
                        // 如果是第一个，则是原订单
                        isOld: index == 0 ? 1 : 0,
                        // 运价（必填）
                        price: it.transportPrice,
                        // 其他费用（必填）
                        otherPrice: it.otherFees,
                        // 提醒师傅现收
                        remDriverCharge: it.remindRouteCash,
                        // 途径高速(选填)
                        highSpeed: it.wayHighSpeed,
                        // 行程简称
                        routeSimpleName: it.routeShort,
                        // 行程详情(必填)
                        routeDetail: it.routeDetail,
                        // 客户备注
                        cusNote: it.cusNote,
                        // 驾驶员备注
                        driverNote: it.driverNote,
                        // 业务员备注
                        serviceNote: it.salesmanNote,
                        // 订单业务类型
                        serviceType: it.orderServiceType,
                        // 每日行程信息
                        dayRouteInfo: dayRouteInfo
                    });
                });

                ps.orderInfo = orderInfos;
            }

            console.log('提交参数对象：', ps);
            if(fg){
                that.fm.sb.load = true;
                let loading = U.qloading('提交中，请稍后...');
                orderService.splitCarOrder(ps).then(res => {
                    that.fm.sb.load = false;
                    U.qclose(loading);
                    
                    if(!res || res.code != 1){
                        U.qerror(res.msg);
                    }else {
                        U.qsuccess(res.msg);

                        // 关闭弹框
                        that.closeMd();

                        // 调用父组件方法-重新加载数据
                        that.$emit('reloadDg');
                    }
                });
            }

        }
    },
    

  }

 }
</script>

<style lang="less" scoped>
    .split-order-list{
        min-width: 1600px;
        margin: 10px 0;
        border: 1px solid #efefef;
        border-radius: 5px;
        display: flex;
        padding: 5px 5px 5px 0;

        // 右边日期列表
        .right-dates{
            margin: 0;
            padding: 0px;
            flex: 150px;
            border-right: 1px solid #efefef;

            li{
                width: 150px;
                list-style: none;
                cursor: pointer;
                padding: 5px;
                border-bottom: 1px solid #efefef;
                position: relative;

                &.curr{
                    border-left: 4px solid #ff6300;
                }

                &:hover{
                    background: #fbfbfb;
                }

                .date{
                    font-size: 15px;
                    font-weight: 600;
                    padding-bottom: 10px;
                }

                .time{
                    font-size: 13px;
                }

                .btns{
                    position: absolute;
                    bottom: 5px;
                    right: 0px;

                    u{
                        font-style: normal;
                        text-decoration: none;
                        padding: 5px;
                        color: #409EFF;
                        opacity: 0.7;

                        &:hover{
                            opacity: 1;
                        }
                    }
                }
            }
        }

        .left-fm ::v-deep{
            flex: calc(100% - 150px);
            padding: 0;

            .route-point{
                margin: 0px;
                margin-bottom: 5px;
                padding: 5px 0 5px 10px;
                border-bottom: 1px solid #efefef; 
            }

            .el-textarea textarea{
                height: 150px !important;
            }
        }
        
    }
</style>